<!--
	作者：offline
	时间：2019-06-03
	描述：业务类型配置
-->
<template>
  <div class="m-view-businessType m-window">
    <div class="m-condition">
      <el-row :gutter="10">
        <el-form label-width="80px" :inline-message="true" label-position="left">
          <el-col :span="8">
            <el-form-item label="编码/名称">
              <el-input v-model="searchValue" placeholder="请输入业务类型编码/名称" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="2" :offset="4">
            <el-checkbox v-model="showState" @change="switchState">显示停用</el-checkbox>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="search(1)">查询</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="add" :disabled="btnDisabled">新增</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="edit" :disabled="showState">编辑</el-button>
          </el-col>
          <el-col :span="2">
            <el-button type="primary" @click="changeState">{{btnText}}</el-button>
          </el-col>
        </el-form>
      </el-row>
    </div>
    <div class="m-agTable m-bottom">
      <ag-grid-vue
        class="m-agTableContent ag-theme-balham"
        :gridOptions="gridOptions"
        :columnDefs="columnDefs"
        :rowData="rowData"
        v-loading="loading"
      ></ag-grid-vue>
    </div>
    <div class="m-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        @prev-click="handlePrevClick"
        @next-click="handleNextClick"
        :current-page="pageInfo.current"
        :page-sizes="[30,50,100,150,200]"
        :page-size="pageInfo.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      ></el-pagination>
    </div>

    <!--新增/编辑弹框 -->
    <el-dialog
      :title="title"
      v-if="dialogVisible"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="业务类型编码" placeholder="请输入业务类型编码" prop="busTypeCode">
          <el-input
            v-model="ruleForm.busTypeCode"
            placeholder="请输入编码"
            clearable
            :disabled="inputDis"
          ></el-input>
        </el-form-item>
        <el-form-item label="业务类型名称" placeholder="请输入名称" prop="busTypeName">
          <el-input v-model="ruleForm.busTypeName" placeholder="请输入名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="上级编码" prop="parentCode">
          <el-cascader
            v-model="ruleForm.parentCode"
            :options="parentOption"
            :props="props"
            :disabled="inputDis"
            :show-all-levels="false"
            @change="cascaderChange"
            clearable
          ></el-cascader>
        </el-form-item>
        <el-form-item label="是否页节点" prop="isLeaf">
          <el-select v-model="ruleForm.isLeaf" placeholder="请选择" :disabled="inputDis">
            <el-option
              v-for="item in sortOption"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排序码" prop="sortCode">
          <el-input v-model="ruleForm.sortCode" placeholder="请输入排序码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose" :disabled.sync="disState">取消</el-button>
        <el-button type="primary" @click="saveData('save')" :disabled.sync="disState">保存</el-button>
        <el-button
          type="primary"
          @click="saveData('continue')"
          :disabled.sync="disState"
          v-if="btnShow"
        >保存并继续</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import _Api from "@/api";
import localeText from "@/i18n/agGridText";
import gridOptions from 'lesso-common/public/gridOptions';
export default {
  data () {
    let checkCode = (rule, value, callback) => {
      if (value) {
        if (!value.trim()) {
          callback(new Error("请输入业务类型编码"));
        } else if (this.busCodes.indexOf(value) < -1) {
          callback(new Error("业务类型编码重复，请重新输入"))
        }
        else
          callback()
      } else {
        callback(new Error("请输入业务类型编码"));
      }
    }
    let checkName = (rule, value, callback) => {
      setTimeout(() => {
        if (value) {
          if (!value.trim()) {
            callback(new Error("请输入业务类型名称"));
          }
          else
            callback()
        } else {
          callback(new Error("请输入业务类型名称"));
        }
      }, 100)
    }
    return {
      // 弹窗标题
      title: '新增业务类型',
      // 弹窗是否显示
      dialogVisible: false,
      // 查询条件 
      searchValue: '',
      // 停用/启用
      btnText: '停用',
      //  表格数据
      rowData: [],
      //  分页信息
      pageInfo: {
        size: 30,
        current: 1,
        total: 0
      },
      // 弹窗表单信息
      ruleForm: {
        busTypeCode: '',
        busTypeName: '',
        parentCode: [],
        isLeaf: 0,
        sortCode: ''
      },
      // 排序下拉内容
      sortOption: [
        { label: '否', value: 0 },
        { label: '是', value: 1 }
      ],
      // 父级编码下拉内容
      parentOption: [],
      // 表单验证规则
      rules: {
        busTypeCode: [
          { required: true, validator: checkCode, trigger: 'blur' }
        ],
        busTypeName: [
          { required: true, validator: checkName, trigger: 'blur' }
        ]
      },
      // 弹窗修改状态   
      mode: '',
      // 级联选择器配置
      props: {
        checkStrictly: true,
        value: 'busTypeCode',
        label: 'busTypeName',
        children: 'childrenList'
      },
      // 已有业务类型编码集合
      busCodes: [],
      inputDis: false,
      btnDisabled: false,
      delShow: false,
      showState: false,
      disState: false,
      loading: false
    }
  },
  beforeMount () {
    //  列表配置
    this.gridOptions = Object.assign({
      context: {
        componentParent: this
      },
      rowSelection: "multiple",
      enableColResize: true,
      localeText: localeText,
      suppressRowClickSelection: true,
      //   getContextMenuItems: this.getContextMenuItems,
      onGridReady: function (params) {
        params.api.sizeColumnsToFit();
      }
    },gridOptions())
    // 列表列信息配置
    this.columnDefs = [
      { headerName: "业务类型编码", field: "busTypeCode", checkboxSelection: true, headerCheckboxSelection: true, headerCheckboxSelectionFilteredOnly: true },
      { headerName: "业务类型名称", field: "busTypeName" },
      { headerName: "父编码", field: "parentCode" },
      {
        headerName: "是否页节点",
        field: "isLeaf",
        cellRenderer: function (params) {
          if (params.value == "1")
            return '<span class="ag-icon">是</span>';
          else if (params.value == "0")
            return '<span class="ag-icon">否</span>';
        }
      },
      { headerName: "排序", field: "sortCode" },
      {
        headerName: "状态",
        field: "state",
        cellRenderer: function (params) {
          if (params.value == "1")
            return '<span class="ag-icon">停用</span>';
          else if (params.value == "0")
            return '<span class="ag-icon">启用</span>';
        }
      }
    ]
  },
  mounted () {
    this.search(1)
  },
  methods: {
    getContextMenuItems () {
      return [];
    },
    // 级联选择器值改变回调
    cascaderChange (val) {
      //   console.log('节点', val)
    },
    // 编辑业务类型
    edit () {
      let row = this.gridOptions.api.getSelectedRows();
      if (row.length <= 0) {
        this.$alert("提示：请选择需要编辑的数据", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt"
        })
        return
      }
      if (row.length > 1) {
        this.$alert("提示：一次只能选择一条数据进行编辑！", {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt"
        })
        return
      }
      this.getParentOptions()
      this.title = "编辑业务类型"
      this.inputDis = true
      this.btnShow = false
      this.ruleForm = row[0]
      this.mode = "edit"
      this.dialogVisible = true
    },
    // 获取业务类型列表数据
    search (flag) {
      if (flag) {
        this.pageInfo.current = 1
      }
      let params = {
        busTypeCode: this.searchValue,
        busTypeName: this.searchValue,
        state: this.showState ? 1 : 0,
        pageSize: this.pageInfo.size,
        currentPage: this.pageInfo.current
      }
      this.loading = true
      _Api.getBusTypeList(params).then((response) => {
        let data = response.data
        this.loading = false
        if (data.code == "1") {
          if (data.total > 0) {
            this.busCodes = data.rows.map(el => {
              return el.busTypeCode
            })
            this.gridOptions.api.setRowData(data.rows.splice(0))
            this.gridOptions.api.sizeColumnsToFit()
            this.pageInfo.total = data.total
          } else {
            this.gridOptions.api.setRowData([])
            this.pageInfo.total = 0
          }
        } else {
          this.$alert(data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          });
        }
        this.loading = false;
      }).catch((err) => {
        this.$alert(err.data.message, {
          showClose: false,
          confirmButton: "确定",
          customClass: "alertFailure"
        })
        this.loading = false;
      })
    },
    // 每页显示条数改变回调
    handleSizeChange (val) {
      this.pageInfo.size = val
      this.search(1)
    },
    // 页码改变回调
    handleCurrentChange (val) {
      this.pageInfo.current = val
      this.search()
    },
    // 点击上一页回调
    handlePrevClick (val) {
      this.pageInfo.current = val
    },
    // 点击下一页回调
    handleNextClick (val) {
      this.pageInfo.current = val
    },
    // 筛选启用状态数据回调
    switchState (val) {
      if (val) {
        this.btnText = "启用"
      } else {
        this.btnText = "停用"
      }
      this.search(1)
    },
    // 停用/启用业务类型
    changeState () {
      let row = this.gridOptions.api.getSelectedRows()
      let msg = this.showState ? '启用' : '停用'
      if (row.length <= 0) {
        this.$alert(`提示：请选择需要${msg}的数据`, {
          showClose: false,
          confirmButtonText: "确定",
          customClass: "alertPrompt"
        })
        return
      }
      // 提取所选业务类型id   
      let busIds = row.map(el => {
        return el.id
      })
      // 提取所选业务类型编码集合
      let codes = row.map(el => {
        return el.busTypeCode
      })
      let params = {
        state: this.showState ? 0 : 1,
        codes: codes.join(','),
        ids: busIds.join(',')
      }
      this.$confirm(`是否确认${msg}已选择的业务类型？`, "消息提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        distinguishCancelAndClose: true
      }).then(() => {
        _Api.changeBusState(params).then(({ data }) => {
          if (data.code == 1) {
            this.$message({
              message: `所选业务类型已${msg}`,
              type: "success"
            })
            this.search(1)
          } else {
            this.$alert(data.info, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            })
          }
        }).catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          })
        })
      }).catch(() => {
        this.$message({
          message: `已取消${msg}`,
          type: "success"
        })
      })
    },
    // 点击新增回调
    add () {
      this.ruleForm = {
        busTypeCode: '',
        busTypeName: '',
        parentCode: [],
        isLeaf: 0,
        sortCode: ''
      }
      this.getParentOptions()
      this.inputDis = false
      this.title = "新增业务类型"
      this.btnShow = true
      this.mode = "add"
      this.dialogVisible = true
    },
    // 关闭弹窗
    handleClose () {
      this.$refs.ruleForm.resetFields()
      this.$refs.ruleForm.clearValidate()
      this.dialogVisible = false
      //   this.search()
    },
    // 保存数据/保存并继续
    saveData (type) {
      const { parentCode } = this.ruleForm
      let params = {
        ...this.ruleForm,
        parentCode: ""
      }
      if (Array.isArray(parentCode)) {
        params.parentCode = parentCode[parentCode.length - 1]
      } else {
        params.parentCode = parentCode
      }
      if (this.mode == "add") {
        this.$refs["ruleForm"].validate((valid) => {
          if (!valid) {
            return false
          }
          this.disState = true
          params.creator = this.$global.user.loginName
          params.creatorId = this.$global.user.id
          _Api.addBusType(params).then((response) => {
            let data = response.data
            if (data.code == "1") {
              this.$message({
                message: "保存成功",
                type: "success"
              })
              //  type为save关闭弹窗，为continue时不关闭弹窗可继续新增  
              if (type == "save") {
                this.dialogVisible = false
              } else {
                this.ruleForm = {
                  busTypeCode: '',
                  busTypeName: '',
                  parentCode: ['order'],
                  isLeaf: 0,
                  sortCode: ''
                }
              }
              this.showState = false
              this.search(1)
            } else {
              this.$alert(data.info, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure"
              })
            }
            this.disState = false
          }).catch((err) => {
            this.$alert(err.data.message, {
              showClose: false,
              confirmButton: "确定",
              customClass: "alertFailure"
            })
            this.disState = false
          })
        })
      } else if (this.mode == "edit") {
        this.$refs["ruleForm"].validate((valid) => {
          if (valid) {
            this.disState = true
            params.modifyer = this.$global.user.loginName
            params.modifyerId = this.$global.user.id
            _Api.updateBusType(params).then((response) => {
              let data = response.data
              if (data.code == "1") {
                this.$message({
                  message: "保存成功",
                  type: "success"
                });
                this.dialogVisible = false
                this.search(1)
              } else {
                this.$alert(data.info, {
                  showClose: false,
                  confirmButton: "确定",
                  customClass: "alertFailure"
                })
              }
              this.disState = false
            }).catch((err) => {
              this.$alert(err.data.message, {
                showClose: false,
                confirmButton: "确定",
                customClass: "alertFailure"
              })
              this.disState = false
            })
          } else {
            return false
          }
        })
      }
    },
    // 获取父级节点下拉内容
    getParentOptions () {
      _Api.getParentsNodes().then(res => {
        let data = res.data
        if (data.code == '1') {
          this.parentOption = data.rows
          setCodeDisabled(this.parentOption)
        } else {
          this.$alert(data.info, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          })
        }
      })
        .catch(err => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: "确定",
            customClass: "alertFailure"
          })
        })
      // 递归设置节点是否可选择
      function setCodeDisabled (arr) {
        arr.forEach(item => {
          if (item.isLeaf == 1) {
            item.disabled = true
          } else {
            item.disabled = false
          }
          if (Array.isArray(item.childrenList)) {
            if (item.childrenList.length > 0) {
              setCodeDisabled(item.childrenList)
            } else {
              item.childrenList = null
            }
          }
        })
      }
    }
  }
}
</script>